package com.woniu.listener;

import com.rabbitmq.client.Channel;
import com.woniu.service.CartService;
import com.woniu.vo.CartVo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
@RabbitListener(queues = "clear.cart.queue")
public class ClearCartListener {
    @Autowired
    private CartService cartService;

    /**
     * 监听清空购物车队列
     * */
    @SneakyThrows
    @RabbitHandler  //指定方法
    public void clearCart(CartVo cartVo, Message message, Channel channel,
                          @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag){
        log.info("清空购物车监听器监听到消息：{}", cartVo);
        try {
            // 执行清理操作
            cartService.clearCart(cartVo.getUserId());

            // 手动确认消费
            channel.basicAck(deliveryTag, false);
            log.info("清空购物车监听器消费消息成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("清空购物车监听器消费消息失败");
            //拒绝消息，重新入队
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            // 获取重投标记
            if (redelivered) {
                log.error("消息已重复消费");
                channel.basicReject(deliveryTag, false);
            } else {
                log.error("消息消费失败，重新入队");
                channel.basicNack(deliveryTag, false, true);
            }

        }



    }

}
